package com.zygh.policeasset.controller;

import cn.hutool.core.util.StrUtil;
import com.zygh.policeasset.component.CommonResult;
import com.zygh.policeasset.component.OperLog;
import com.zygh.policeasset.mapper.UserMapper;
import com.zygh.policeasset.pojo.User;
import com.zygh.policeasset.service.MenuService;
import com.zygh.policeasset.service.TokenService;
import com.zygh.policeasset.utils.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping({"/public/auth"})
@Api(tags = {"用户登陆身份验证"})
@RestController
public class AuthController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    UserMapper userMapper;

    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CommonResult.class)})
    @RequestMapping(value = {DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL}, method = {RequestMethod.POST})
    @ApiOperation("用户名和密码登陆，获取Token")
    @OperLog(operModul = "用户登录", operType = "查询", operDesc = "用户登录")
    public Object userNameLogin(@RequestBody User params) {

        if (StrUtil.isEmpty(params.getUsername())) {
            return new CommonResult().validateFailed("用户名不能为空");
        }
        if (StrUtil.isEmpty(params.getPassword())) {
            return new CommonResult().validateFailed("密码不能为空");
        }

        Object token = this.tokenService.getTokenByName(params.getUsername(), params.getPassword());
        if (token == null) {
            return new CommonResult().validateFailed("登录失败,用户名和密码不匹配");
        }
        if (!StringUtils.isEmpty(params.getType())) {
            String uuid = userMapper.selectUuid(params.getUsername());
            if (!StringUtils.isEmpty(uuid)) {
                if (!uuid.equals(params.getUuid())) {
                    return new CommonResult().validateFailed("该手持设备已绑定用户,如需继续使用,请联系管理员解绑");
                }
            } else {
                userMapper.updateUuidByUserName(params.getUuid(), params.getUsername());
            }
        }

        Map<String, Object> data = new HashMap<>(16);
        data.put("token", token);
        return new CommonResult().success(data);
    }

    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = CommonResult.class)})
    @RequestMapping(value = {"/getUserByToken"}, method = {RequestMethod.GET})
    @ApiOperation("根据Token获取用户信息")
    public Object getUserByToken(HttpServletRequest request) {
        String username;
        String authHeader = request.getHeader("token");
        if (authHeader == null || !authHeader.startsWith(this.tokenHead) || (username = this.jwtTokenUtil.getUserNameFromToken(authHeader.substring(this.tokenHead.length()))) == null) {
            return new CommonResult().validateFailed("此用户不存在");
        }
        Object user = this.menuService.findMenuByUserId(username);
        Map<String, Object> data = new HashMap<>(16);
        data.put("user", user);
        return new CommonResult().success(data);
    }
}